﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using YWTSSys.Model;
using YWTSSys.BLL;
using YWTSSys.Library;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Configuration;
namespace YWTSSys.Web
{
    /// <summary>
    /// 页面基类
    /// </summary>
    public abstract class PageBase : System.Web.UI.Page
    {
        protected void PageBase_Error(object sender, EventArgs e)
        {
            Exception currentError = Server.GetLastError();
            try
            {
                if (currentError == null)
                {
                    return;
                }
                if (currentError is WebException)
                {
                    ((WebException)currentError).Handle();
                }
                else
                {
                    string friendlyMsg = currentError.Message;
#if　DEBUG　　//　如果程序处于Debug状态，则直接在页面显示具体不正确信息，便于调试
                    friendlyMsg = currentError.Message + "<br　/>Stack:" + currentError.StackTrace;
                    Response.Write(friendlyMsg);

#else
                WebException exc= new WebException(friendlyMsg);
                exc.Handle();
#endif
                }
            }
            finally
            {
                SLogInfo obj = new SLogInfo();
                obj.LogType = "错误";
                obj.DWZRef = this.DWZRef;
                obj.RealName = User.RealName;
                obj.OpOldObj = currentError.Message;

                SLogController.Add(obj);
            }

            Server.ClearError();
        }
        protected override void OnInit(EventArgs e)
        {
            this.Error += new System.EventHandler(this.PageBase_Error);
            base.OnInit(e);
            //验证权限规证
            if (!User.IsSuperAdmin)
            {
                if (MustLogin)
                {
                    if (!Request.IsAuthenticated)
                        throw new NeedLoginException("请先登陆");
                }
               
                if (!HasPower(PowerKey))
                {
                    throw new NoPowerException("您没有权限进入此页面");
                }
            }            
        }

        #region 日志相关

        protected void AddLog(SLogInfo obj)
        {
            SLogController.Add(obj);
        }

        protected void AddLog(Permission per, object oldobj, object newobj)
        {
            SLogInfo obj = new SLogInfo();
            obj.LogType = "操作";
            obj.OpType = per.ToString();
            obj.DWZRef = this.DWZRef;
            obj.RealName = User.RealName;
            obj.OpOldObj =oldobj==null?"": oldobj.SerializableToXml();
            obj.OpNewObj =newobj==null?"": newobj.SerializableToXml();
            SLogController.Add(obj);
        }

        protected void AddLog(Permission per, object oldobj)
        {
            AddLog(per, oldobj, null);
        }

        protected void AddLog(Permission per)
        {
            AddLog(per, null, null);
        }
        #endregion
        #region 页面参数获取
        protected T GetRequestValue<T>(string name)
        {
            return Request.GetRequestValue<T>(name);
        }

        protected T GetRequestValue<T>(string name, bool useDefValue, T defValue)
        {
            return Request.GetRequestValue<T>(name, useDefValue, defValue);
        }
        protected T GetRequestValue<T>(string name, T defValue)
        {
            return Request.GetRequestValue<T>(name, true, defValue);
        }
        #endregion
        private string _DWZRef = "";
        /// <summary>
        /// DWZ框架中的页面ID，用于服务器转回navTabId可以把那个navTab标记为reloadFlag=1, 下次切换到那个navTab时会重新载入内容
        /// </summary>
        protected abstract string DWZRef
        {
            get;
        }
        #region 操作JSON
        

        public enum callbackType
        {
            forward,
            closeCurrent
        }
        /// <summary>
        /// 输入操作JOSN
        /// </summary>
        /// <param name="statusCode">200表示成功,300表示失败</param>
        /// <param name="message">操作提示消息</param>
        /// <param name="navTabId">服务器转回navTabId可以把那个navTab标记为reloadFlag=1, 下次切换到那个navTab时会重新载入内容</param>
        /// <param name="callbackType">callbackType如果是closeCurrent就会关闭当前tab,只有callbackType="forward"时需要forwardUrl值</param>
        /// <param name="forwardUrl">重新加的页面路径</param>
        /// <returns></returns>
        private void ResponseOpJson(string statusCode, string message, string navTabId, callbackType callbackType, string forwardUrl)
        {
            Response.Clear();
            Response.ContentType = "text/plain";
            Response.BufferOutput = true;

            Response.Write(ResponseOpJson2(statusCode, message, navTabId, callbackType.ToString(), forwardUrl));
          
            Response.End();
        }
        private void ResponseOpJson(string statusCode, string message, string navTabId, string callbackType, string forwardUrl)
        {
            Response.Clear();
            Response.ContentType = "text/plain";
            Response.BufferOutput = true;

            Response.Write(ResponseOpJson2(statusCode, message, navTabId, callbackType.ToString(), forwardUrl));

            Response.End();
        }

        private string  ResponseOpJson2(string statusCode, string message, string navTabId, string callbackType, string forwardUrl)
        {
            string jsontemp = "{{\"statusCode\":\"{0}\",\"message\":\"{1}\",\"navTabId\":\"{2}\",\"callbackType\":\"{3}\",\"forwardUrl\":\"{4}\"}}";
            return string.Format(jsontemp, statusCode, message, navTabId, callbackType.ToString(), forwardUrl);
        }

        protected void ShowTopSuccessJson(string statusCode, string message, string navTabId, string callbackType, string forwardUrl)
        {
            Response.Clear();
            Response.ContentType = "text/plain";
            Response.BufferOutput = true;

            Response.Write("<script>top.navTabAjaxDone("+ResponseOpJson2(statusCode, message, navTabId, callbackType.ToString(), forwardUrl)+");</script>");

            Response.End();
        }
        protected void ShowTopSuccessJson(string message)
        {
            ShowTopSuccessJson("200", message, DWZRef, callbackType.closeCurrent.ToString(), "");
        }


        protected void SuccessJson(string message,string navTabId, string forwardUrl)
        {
            ResponseOpJson("200", message, navTabId, callbackType.forward, forwardUrl);
        }
        protected void SuccessJson(string message,string navTabId)
        {
            ResponseOpJson("200", message, navTabId, callbackType.closeCurrent, "");
        }
        protected void SuccessJson(string message)
        {
            ResponseOpJson("200", message, this.DWZRef, callbackType.forward, "");
        }

        protected void ErrorJson(string message, string navTabId,string forwardUrl)
        {
            ResponseOpJson("300", message, navTabId, callbackType.forward, forwardUrl);
        }
        protected void ErrorJson(string message, string navTabId)
        {
            ResponseOpJson("300", message, navTabId, callbackType.closeCurrent, "");
        }
        protected void ErrorJson(string message)
        {
            ResponseOpJson("300", message, this.DWZRef, callbackType.closeCurrent, "");
        }

        protected void AlertJson(string message)
        {
            ResponseOpJson("300", message, "", callbackType.closeCurrent, "");
        }

        protected void SuccessAlertJson(string message)
        {
            ResponseOpJson("200", message, "#", "", "");
        }
        #endregion

        #region 权限相关
        /// <summary>
        /// 访问此页面是否需要登陆
        /// </summary>
        protected virtual bool MustLogin
        {
            get
            {
                return true;
            }
        }
        /// <summary>
        /// 访问此页面所属的权限
        /// </summary>       
        protected virtual Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.none };
            }
        }
        /// <summary>
        /// 当前用户
        /// </summary>
        public OUserInfo User { get { return OUserController.CurrentUser; } }
        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="per"></param>
        /// <returns></returns>
        public bool HasPower(Permission per)
        {
            if (User.IsSuperAdmin)
                return true;
            if (per==Permission.none)
                return true;
            int MenuId = 0;
            List<OMenuInfo> allMenuDT = OMenuController.GetAllOMenu2();
            MenuId= allMenuDT.Find(e => e.DWZRel.ToLower() == DWZRef.ToLower()).MenuId;

            List<OMenuPermissionInfo> alper = ORoleController.GetPermissionByRoleId(OUserController.CurrentUser.RoleId);

            OMenuPermissionInfo obj =alper.Find(e => e.MenuId == MenuId && e.PermissionTag == per.ToString());

            return obj == null ? false : true;
        }
        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="per"></param>
        /// <returns></returns>
        public bool HasPower(Permission[] per)
        {
            return HasPower(this.DWZRef, per);
        }

        public bool HasPower(string DWZRel,Permission[] per)
        {
            if (User.IsSuperAdmin)
                return true;
            if (per.Length <= 1)
            {
                if (per[0] == Permission.none)
                    return true;
            }
            int MenuId = 0;
            List<OMenuInfo> allMenuDT = OMenuController.GetAllOMenu2();
            MenuId = allMenuDT.Find(e => e.DWZRel.ToLower() == DWZRel.ToLower()).MenuId;

            List<OMenuPermissionInfo> alper = ORoleController.GetPermissionByRoleId(OUserController.CurrentUser.RoleId);

            bool r = false;
            foreach (Permission p in per)
            {
                OMenuPermissionInfo obj = alper.Find(e => e.MenuId == MenuId && e.PermissionTag == p.ToString());

                r = obj == null ? false : true;
                if (r)
                    break;
            }

            return r;
        }
        #endregion
        #region 列表页相关属性
        /// <summary>
        /// 当关闭处理页时，是否刷新列表页
        /// </summary>
        protected bool IsRefreshPar
        {
            get
            {
                return GetRequestValue<bool>("isrefreshpar", true);
            }
        }
        /// <summary>
        /// 排序字段 值为 id
        /// </summary>
        protected virtual string orderField
        {
            get
            {
                return GetRequestValue<string>("orderField", "");
            }
        }
        /// <summary>
        ///  排序方式 desc或 asc
        /// </summary>
        protected virtual string orderDirection
        {
            get
            {
                return GetRequestValue<string>("orderDirection", "desc");
            }
        }
        /// <summary>
        /// 获取当前排序列的显示方式
        /// 格式为 orderfield="" class=""
        /// </summary>
        /// <param name="ordercolumn">需排序的列名</param>
        /// <returns></returns>
        protected string GetDataListOrder(string ordercolumn)
        {
            string defaultascdesc = "desc";

            return string.Format("orderField=\"{0}\" class=\"{1}\"",ordercolumn, ordercolumn.Trim().ToLower() != orderField.Trim().ToLower() ? "defaultorder" : ordercolumn.ToLower().Trim() == orderField.ToLower().Trim() ? orderDirection.Trim().ToLower() == "asc" ? "asc" : "desc" : defaultascdesc);
        }
        protected virtual string SQLSort
        {
            get
            {
                return orderField + " " + orderDirection;
            }
        }
        /// <summary>
        /// 当前显示的页数,默认值为1
        /// </summary>
        protected int pageNum
        {
            get
            {
                return GetRequestValue<int>("pageNum",1);
            }
        }
        /// <summary>
        /// 每页显示条数,默认20
        /// </summary>
        protected int numPerPage
        {
            get
            {
                return GetRequestValue<int>("numPerPage", GetMySettingValue("MyNumPerPage") == "" ? 20 : Convert.ToInt32(GetMySettingValue("MyNumPerPage")));               
            }
        }
        /// <summary>
        /// 查询后总记录总条数
        /// </summary>
        protected int TotalCount = 0;

        protected string SetnumPerPage()
        {
            return SetnumPerPage(numPerPage.ToString());
        }
        protected string SetnumPerPage(string selectvalue)
        {
            string html = "";
            selectvalue = string.IsNullOrEmpty(selectvalue) ? "20" : selectvalue;
            int iselectvalue = Convert.ToInt32(selectvalue);
            string optiontemp = "<option value=\"{0}\" {1}>{0}</option>";
            html = html + string.Format(optiontemp, 10, iselectvalue == 10 ? "selected" : "");
            html = html + string.Format(optiontemp, 20, iselectvalue == 20 ? "selected" : "");
            html = html + string.Format(optiontemp, 50, iselectvalue == 50 ? "selected" : "");
            html = html + string.Format(optiontemp, 100, iselectvalue == 100 ? "selected" : "");
            html = html + string.Format(optiontemp, 200, iselectvalue == 200 ? "selected" : "");
            html = html + string.Format(optiontemp, 300, iselectvalue == 300 ? "selected" : "");
            return html;
        }
        #endregion


        protected string[] macTypeList = new string[] { "55NS", "55NSL", "60NS", "65NS", "65NSL", "80NS", "80NX", "80NC", "45N", "35N", "17VX3" };
        /// <summary>
        /// 获取自动
        /// </summary>
        /// <param name="responseType"></param>
        /// <param name="controlName"></param>
        /// <param name="selectValue"></param>
        /// <returns></returns>
        protected string GetMacType(string responseType, string controlName, string selectValue)
        {
           
            string htmlr = "";
            switch (responseType.ToLower().Trim())
            { 
                case "select":
                    htmlr = string.Format("<select name=\"{0}\" class='combox'>",controlName);
                    htmlr += string.Format("<option value=\"{0}\" {1}>{2}</option>", "", "" == selectValue ? "selected" : "","请选择...");
                    foreach (string item1 in macTypeList)
                    {
                        htmlr += string.Format("<option value=\"{0}\" {1}>{0}</option>", item1, item1 == selectValue?"selected":"");
                    }
                    htmlr =htmlr+ "</select>";
                    break;
                case "checkbox":
                  
                    foreach (string item1 in macTypeList)
                    {
                        string c = "";
                        foreach (string tt in selectValue.Split(new char[] { ',' }))
                        {
                            c = tt == item1 ? "chcecked" : "";
                            if (tt == item1)
                            {
                                c = "checked";
                                break;
                            }
                        }
                        htmlr += string.Format("<input type=\"checkbox\" name=\"{0}\" {1} value=\"{2}\">{2}", controlName, c, item1);
                    }
                   
                    break;
                case "radio":

                    foreach (string item1 in macTypeList)
                    {
                        string macsuff = item1 == "55NS" || item1 == "55NSL" ? "XB" : item1 == "60NS" || item1 == "65NS" || item1 == "65NSL" ? "WJ" :item1=="17VX3"?"WR": "XC";

                        htmlr += string.Format("<input type=\"radio\" name=\"{0}\" {1} value=\"{2}\" macsuff=\"{3}\">{2}", controlName, item1 == selectValue ? "checked" : "", item1, macsuff);
                    }
                    break;
            }
            return htmlr;
        }
        /// <summary>
        /// 根据机号获取机型
        /// </summary>
        /// <param name="SerialNumber"></param>
        /// <returns></returns>
        protected string GetMacTypeBySerialNumber(string SerialNumber)
        {
            //"55NS", "55NSL", "60NS", "65NS","65NSL", "80NS","80NX"
            Dictionary<string, string> mactypelist = new Dictionary<string, string>();
            mactypelist.Add("XB0", "55NSL");
            mactypelist.Add("WJ0", "65NS");
            mactypelist.Add("WJ1", "65NSL");
            mactypelist.Add("XC1", "80NS");
            mactypelist.Add("XC0", "80NC");
            mactypelist.Add("WR0", "17VX3");
            if (SerialNumber.Length <= 3)
                return "";
            string key = SerialNumber.Substring(0, 3).ToUpper();
            try
            {
                return mactypelist.First(e => e.Key == key).Value;
            }
            catch
            {
                return "";
            }

        }

        /// <summary>
        /// 导出到Execl
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="control"></param>
        protected void ExportToExecl(string filename, Control control)
        {
            // this.rpMenu.DataSource = OInspectionController.GetPagination(MachineType, SerialNumber, DownlineDateFrom, DownlineDateTo, DJNGItemCode, BZNGItemCode, pageNum, numPerPage, SQLSort, ref TotalCount);
            // this.rpMenu.DataBind();

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            Page page = new Page();
            HtmlForm form = new HtmlForm();
            // GridView GridView1 = new GridView();
            control.EnableViewState = false;
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            page.Controls.Add(form);
            form.Controls.Add(control);
            page.RenderControl(htw);
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "Application/ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filename) + ".xls");
            Response.Charset = "";
            Response.ContentEncoding = System.Text.Encoding.UTF8;          
            Response.Write(sb.ToString());
            Response.End();
        }
        /// <summary>
        /// 获取个人设置
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        protected string GetMySettingValue(string Key)
        {

            string[] MySettingsArr = User.MySetting.Split(new char[] { ',' });
            foreach (string aitem in MySettingsArr)
            {
                string[] items = aitem.Split(new char[] { '|' });
                if (items[0].ToUpper() == Key.ToUpper())
                    return items[1];
            }
            return "";
        }


        #region 各数据分担功能服务器及路径配置 2012-03-01
        private  string _AutoCompleteRequestUrl = "";
        /// <summary>
        /// 获取自动完成服务的URL地址
        /// </summary>
        protected  string AutoCompleteRequestUrl
        {
            get
            {
                try
                {
                    if (_AutoCompleteRequestUrl == "")
                    {
                        string AutoCompleteRequestUrlAppConfig = Request.GetUserRequstSoure() ? "AutoCompleteRequestUrl" : "OutSideNetAutoCompleteRequestUrl";
                        _AutoCompleteRequestUrl = ConfigurationManager.AppSettings[AutoCompleteRequestUrlAppConfig];
                    }
                }
                catch
                {
                    _AutoCompleteRequestUrl = "sysAjaxDone.ashx";// "http://192.168.1.19:82/AutoCompleteRequest.ashx";
                }
                return _AutoCompleteRequestUrl;
            }
        }
        #endregion
    }
}